﻿using SelfManagement.Database.POCO;
using SelfManagement.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using SelfManagement.Utility.Extensions;
using Ninject;

namespace SelfManagement.Services
{
    public class ArticleCategoryService: BaseService<ArticleCategory>, IArticleCategoryService
    {
        [Inject]
        public IArticleService ArticleService { get; set; }

        public IQueryable<ArticleCategory> QueryUserArticleCategories(string uid)
        {
            return Query(c => c.User_Id == uid);
        }

        public List<ArticleCategory> GetUserArticleCategories(string uid)
        {
            return QueryUserArticleCategories(uid).ToList();
        }

        public ArticleCategory GetUserArticleCategoryById(string uid, string id)
        {
            return QueryUserArticleCategories(uid).Where(c => c.Id == id).FirstOrDefault();
        }
        
        public string GetUserArticleDefautCategoryId(string uid)
        {
            return QueryUserArticleCategories(uid).Where(c => c.IsDefault).FirstOrDefault()?.Id;
        }


        /// <summary>
        /// 将文章转移到默认分类
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public bool TransferArticlesToDefaultCategory(string uid, string categoryId)
        {
            string defaultCategoryId = GetUserArticleDefautCategoryId(uid);
            return ArticleService.UpdateBatch(a => a.User_Id == uid && a.Category_Id == categoryId,
                a => {
                    a.Category_Id = defaultCategoryId;
                    return a;
                });
        }

        /// <summary>
        /// 删除文章分类
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteUserCategoryById(string uid, string id)
        {
            ArticleCategory category = GetUserArticleCategoryById(uid, id);
            if (category.IsDefault) {
                throw new Exception("不支持删除默认分类");
            }
            TransferArticlesToDefaultCategory(uid, id);
            return DeleteBatch(c => c.User_Id == uid && c.Id == id);
        }


        /// <summary>
        /// 通过分类名称，判断文章分类是否存在
        /// </summary>
        /// <param name="uid">用户id</param>
        /// <param name="category">分类实体</param>
        /// <returns></returns>
        public bool IsExistsUserCategoryByName(ArticleCategory category)
        {
            ArticleCategory exists = GetUserArticleCategories(category.User_Id).FirstOrDefault(
                c => c.CategoryName.Equals(category.CategoryName));
            return exists.IsNotNull() && !exists.Id.Equals(category.Id);
        }

    }
}
